import React , {Component} from "react";
import {  Divider ,Button , Spin, Upload ,Form ,Space } from "antd";
import PropTypes from 'prop-types';
import AppBar from '@material-ui/core/AppBar';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import Typography from '@material-ui/core/Typography';
import { InboxOutlined } from '@ant-design/icons';
const { Dragger } = Upload;
import MyTable from "../../compontens/MyTable";
import { Link, withRouter } from 'react-router-dom';
import axios from 'axios';
import './index.css';

const formItemLayout = {
    labelCol: {
      span: 4,
    },
    wrapperCol: {
      span: 14,
    },
  };
  
  

  function TabContainer(props) {
    return (
      <Typography component="div" style={{ padding: 8 * 3 }}>
        {props.children}
      </Typography>
    );
  }
  
  TabContainer.propTypes = {
    children: PropTypes.node.isRequired,
  };


export default class Data_preprocessing extends Component{
    constructor(props){
        super(props);
        this.state = {
            value: 0,
            loading: false,
            dataList: {},
            example_se_data_columns: 
            [
                {
                  key: 'SampleID',
                  dataIndex: 'SampleID',
                  title: 'SampleID',
                },
                {
                  key: 'Group',
                  dataIndex: 'Group',
                  title: 'Group',
                },
                {
                  key: 'Reads_files',
                  dataIndex: 'Reads_files',
                  title: 'Reads_files',
                render: (text) => {
                    return <a onClick={() => this.DownLoadReadFiles(text)}>{text}</a>
                }
                },
            ],
            example_se_data: [
            {
                key: '1',
                SampleID: 'M0018C_birth',
                Group: 'infant',
                Reads_files: 'SRR7281057_sub_1.fastq.gz',
            },{
                key: '2',
                SampleID: 'M0018C_14_day',
                Group: 'infant',
                Reads_files: 'SRR7281059_sub_1.fastq.gz',
            },{
                key: '3',
                SampleID: 'M0018C_1_month',
                Group: 'infant',
                Reads_files: 'SRR7281058_sub_1.fastq.gz',
            },{
                key: '4',
                SampleID: 'M0018C_2_month',
                Group: 'infant',
                Reads_files: 'SRR7281046_sub_1.fastq.gz',
            },{
                key: '5',
                SampleID: 'M0018C_3_month',
                Group: 'infant',
                Reads_files: 'SRR7280802_sub_1.fastq.gz',
            },{
                key: '6',
                SampleID: 'M0018M_birth',
                Group: 'mother',
                Reads_files: 'SRR7280884_sub_1.fastq.gz',
            },{
                key: '7',
                SampleID: 'M0018M_gest',
                Group: 'mother',
                Reads_files: 'SRR7280946_sub_1.fastq.gz',
            },{
                key: '8',
                SampleID: 'M0018M_3_month',
                Group: 'mother',
                Reads_files: 'SRR7280885_sub_1.fastq.gz',
            }],
        }
        this.onFinish = this.onFinish.bind(this);
        this.RFile = this.RFile.bind(this);
        this.GFile = this.GFile.bind(this);
    }
    RFile = (event) => {
      if (Array.isArray(event)) {
        return event;
      }
      const { file, fileList } = event;
      return fileList;
    }

    GFile = (event) => {
      console.log(event)
      const { file, fileList } = event;
      if(fileList.length>1){
        alert('please input one file！')
        fileList.pop()
      }
      if (Array.isArray(event)) {
        return event;
      }
      return fileList;
    }
      
    onFinish = (values) => {
      // loading=true
      this.setState({loading:true})
        if(values.rdragger==undefined || values.gdragger==undefined){
          alert('please input file！')
          return
        }
        let data =new FormData()
        const files = values.rdragger
        files.forEach((file) => {
          data.append("file",file.originFileObj)
        });
        const group = values.gdragger[0].originFileObj
        data.append("group",group)
        axios({
          headers: {
            'Content-Type':'application/json'
          },
            method: 'post',
            url:`http://127.0.0.1:5000/upload`,
            data: data,
          }).then(res => {
            this.setState({loading:false})
            if(res && res.status === 200){
              alert('upload success！')
              console.log(res)
              localStorage.setItem('Kra_result', res.data);
              localStorage.setItem('defaultValue', res.data.IDList[0]);
              const { history } = this.props;
              history.push('/identification');
            }else{
              console.log('error')
            }
          })
          .catch(err => {
            this.setState({loading:false})
            alert('error！')
            console.log(err)
          }
          )
          
      };
    onSampleSeFinish = (values) => {
        const { history } = this.props;
        const params = {
            name: 'example'
          };
        history.push('/kraken', { state: "example" }); 
    };
    handleChange = (event, value) => {
        this.setState({ value: value });
    };

    DownLoadReadFiles = (e) => {
        const title = e;
        const fileUrl = 'public/example_files/test_data/'+title; // 文件的实际路径
        const fileName = title; // 下载后的文件名
        fetch(fileUrl)
          .then(response => response.blob())
          .then(blob => {
            const url = window.URL.createObjectURL(new Blob([blob]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', fileName);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
          })
          .catch(error => console.log(error));
        };

    render(){
        const value = this.state.value;
        const example_se_data_columns = this.state.example_se_data_columns;
        const example_se_data = this.state.example_se_data;
        return(
        <>
            <Divider orientation="left">Upload Files  </Divider>
            <Spin spinning={this.state.loading} tip="Loading...">
            <AppBar position="static" color="default">
            <Tabs
                value={value}
                onChange={this.handleChange}
                indicatorColor="primary"
                textColor="primary"
                variant="scrollable"
                scrollButtons="auto"
            >
                <Tab label="Upload" />
                <Tab label="Single Example Datas" />
            </Tabs>
            </AppBar>
            {value === 0 && <TabContainer>
                <Form
                name="validate_other"
                {...formItemLayout}
                onFinish={this.onFinish}
                className="upload-form"            >
                <Form.Item label="Reads Files">
                <Form.Item name="rdragger" valuePropName="RfileList" getValueFromEvent={this.RFile} noStyle>
                    <Upload.Dragger name="rfiles" multiple action={"http://127.0.0.1:5000/upload"}>
                    <p className="ant-upload-drag-icon">
                        <InboxOutlined />
                    </p>
                    <p className="ant-upload-text">Click or drag file to this area to upload</p>
                    <p className="ant-upload-hint">Support for a single or bulk upload.</p>
                    </Upload.Dragger>
                </Form.Item>
                </Form.Item>
                <Form.Item label="Groups Files">
                <Form.Item name="gdragger" valuePropName="GfileList" getValueFromEvent={this.GFile} noStyle>
                    <Upload.Dragger name="gfiles" action={"http://127.0.0.1:5000/upload"}>
                    <p className="ant-upload-drag-icon">
                        <InboxOutlined />
                    </p>
                    <p className="ant-upload-text">Click or drag file to this area to upload</p>
                    <p className="ant-upload-hint">Support for a single or bulk upload.</p>
                    </Upload.Dragger>
                </Form.Item>
                </Form.Item>
                <Form.Item
                className="upload-form-button"
                wrapperCol={{
                    span: 9,
                    offset: 9,
                }}
                >
                <Space className="upload-form-button">
                    <Button type="primary" htmlType="submit">
                    Submit
                    </Button>
                    <Button htmlType="reset">reset</Button>
                </Space>
                </Form.Item>
            </Form>
            </TabContainer>}
            {value === 1 && <TabContainer>
                <Form
                name="validate_other"
                onFinish={this.onSampleSeFinish}
                className="upload-form">
                <Form.Item>
                    <MyTable
                    columns={example_se_data_columns} 
                    dataSource={example_se_data}></MyTable>
                </Form.Item>
                <Form.Item
                className="upload-form-button"
                wrapperCol={{
                    span: 9,
                    offset: 9,
                }}
                >
                <Space className="upload-form-button">
                    <Button type="primary" htmlType="submit">
                    Submit
                    </Button>
                </Space>
                </Form.Item>
            </Form>
            </TabContainer>}  
            </Spin>          
        </>
        )
    }
}